import socket
from google.protobuf import text_format
from google.protobuf import json_format
import args_pb2
import json

if __name__ == "__main__":

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('127.0.0.1', 9000))
    sock.listen(5)
    while True:
        connection, address = sock.accept()
        try:
            # connection.settimeout(5)
            data = connection.recv(1024)
            # if data == '1':
            #     connection.send('welcome to server!')
            # else:
            print('request:',data)
            #
            # obj = args_pb2.Args()
            #
            # obj.args1 = 13
            # obj.args2 = 12
            # obj.flag = 1
            #
            # # 序列化成二进制
            # print(obj.SerializeToString())

            # 从二进制反序列化
            obj = args_pb2.Args()
            obj.ParseFromString(data)
            str_json = json_format.MessageToJson(obj, True)
            # print(type(str))
            json_str = json.loads(str_json);
            print('pojo:', json_str)
            # connection.send(str.encode('please go out!\r\n'))
            if json_str['flag'] == 1:
                connection.send(str.encode(str(json_str['args1'] + json_str['args2']) + '\r\n'))
            if json_str['flag'] == 2:
                connection.send(str.encode(str(json_str['args1'] -json_str['args2']) + '\r\n'))
        # except socket.socket.timeout:
        #     print
        #     'time out'
        except Exception:
            print('异常'+Exception);
    connection.close()



    # obj = args_pb2.Args()
    #
    # obj.args1 = 13
    # obj.args2 = 12
    # obj.flag = 1
    #
    # # 序列化成二进制
    # print(obj.SerializeToString())
    #
    # # 从二进制反序列化
    # obj1 = args_pb2.Args()
    # obj1.ParseFromString(obj.SerializeToString())
    #
    # # 转换成字典
    # print(json_format.MessageToDict(obj1, True))
    #
    # # 从json数据反序列化
    # obj2 = args_pb2.Args()
    #
    # print("222:  ",json_format.MessageToJson(obj1, True))
    # json_format.Parse(json_format.MessageToJson(obj1, True), obj2)
    # print(obj2)
    # obj.orgs1 = 1

    # print(obj)














